package com.rongchuang.service;

import com.querydsl.jpa.impl.JPAQueryFactory;
import com.rongchuang.entity.RolePermission;
import com.rongchuang.repository.RolePermissionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class RolePermissionService {

    @Autowired
    private RolePermissionRepository rolePermissionRepository;

    @Autowired
    private JPAQueryFactory queryFactory;

    @Transactional(rollbackFor = Exception.class)
    public void addPermission(Long roleId, List<Long> permissionIds) {
        // 删除当前角色权限
        rolePermissionRepository.deleteByRoleId(roleId);

        // 新增角色当前权限
        List<RolePermission> permissions = permissionIds.stream().map(e -> {
            RolePermission permission = new RolePermission();
            permission.setRoleId(roleId);
            permission.setPermissionId(e);
            return permission;
        }).collect(Collectors.toList());
        rolePermissionRepository.saveAll(permissions);
    }
}
